package org.esk.dablog.web.forms;

import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.validation.BindException;
import org.esk.dablog.web.util.RequestUtils;
import org.esk.dablog.web.functions.EntryFunctions;
import org.esk.dablog.service.EntryManager;
import org.esk.dablog.service.PictureManager;
import org.esk.dablog.model.Picture;
import org.esk.dablog.exceptions.BusinessException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This class is used to edit Picture's properties
 * User: jc
 * Date: 30.11.2006
 * Time: 11:59:49
 * $Id:$
 */
public class EditPictureForm extends SimpleFormController {
    private PictureManager pictureManager;


    /**
     * 
     */
    public EditPictureForm() {
        this.setCommandClass(Picture.class);
    }


    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
        Picture pic = (Picture) command;
        pictureManager.savePicture(pic);      
        return new ModelAndView(getSuccessView());
    }


    protected void onBind(HttpServletRequest request, Object command, BindException errors) throws Exception {
        Picture pic = (Picture) command;
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        MultipartFile file = req.getFile("photo");
        pic.setData(file.getBytes());
        super.onBind(request, command, errors);
    }

    protected Object formBackingObject(HttpServletRequest request) throws Exception {
        long id = RequestUtils.extractLongParameter(request);
        Picture pic = pictureManager.getPicture(id);
        if (!EntryFunctions.isPictureOwner(pic, request.getRemoteUser())) {
            throw new BusinessException("User " + request.getRemoteUser() + " cannot edit picture id " + id
                    + " belonging to user " + pic.getAuthor().getUsername());
        }
        return pic;
    }


    public void setPictureManager(PictureManager pictureManager) {
        this.pictureManager = pictureManager;
    }
}
